const fs = require('fs');
const path = require('path');
const initSqlJs = require('sql.js');

// 数据库文件路径
const dbPath = path.join(__dirname, 'warehouse.db');
const auditSqlPath = path.join(__dirname, 'audit-trigger.sql');

async function setupAudit() {
  try {
    const SQL = await initSqlJs();
    
    // 检查数据库文件是否存在
    if (!fs.existsSync(dbPath)) {
      console.log('❌ 数据库文件不存在:', dbPath);
      return;
    }
    
    // 从文件加载数据库
    const fileBuffer = fs.readFileSync(dbPath);
    const db = new SQL.Database(fileBuffer);
    console.log('✅ 数据库已加载');
    
    // 读取审计SQL脚本
    if (!fs.existsSync(auditSqlPath)) {
      console.log('❌ 审计SQL脚本文件不存在:', auditSqlPath);
      return;
    }
    
    const auditSql = fs.readFileSync(auditSqlPath, 'utf8');
    console.log('✅ 审计SQL脚本已加载');
    
    // 分割SQL语句并执行
    const statements = auditSql
      .split(';')
      .map(stmt => stmt.trim())
      .filter(stmt => stmt.length > 0);
    
    console.log(`🔍 准备执行 ${statements.length} 条SQL语句`);
    
    for (let i = 0; i < statements.length; i++) {
      const stmt = statements[i];
      if (stmt.startsWith('--') || stmt.startsWith('/*')) {
        // 跳过注释
        continue;
      }
      
      try {
        console.log(`📝 执行语句 ${i + 1}:`, stmt.substring(0, 50) + (stmt.length > 50 ? '...' : ''));
        db.run(stmt);
        console.log(`✅ 语句 ${i + 1} 执行成功`);
      } catch (error) {
        console.error(`❌ 语句 ${i + 1} 执行失败:`, error.message);
        console.error('语句内容:', stmt);
      }
    }
    
    // 保存数据库
    const data = db.export();
    const buffer = Buffer.from(data);
    fs.writeFileSync(dbPath, buffer);
    console.log('💾 数据库已保存');
    
    console.log('✅ 审计触发器设置完成');
    
    // 查询审计表信息
    try {
      console.log('🔍 查询审计表信息...');
      const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%audit%'");
      const tableRows = [];
      while (tables.step()) {
        tableRows.push(tables.getAsObject());
      }
      console.log('📊 审计相关表:', tableRows);
      
      if (tableRows.length > 0) {
        const triggers = db.prepare("SELECT name FROM sqlite_master WHERE type='trigger'");
        const triggerRows = [];
        while (triggers.step()) {
          triggerRows.push(triggers.getAsObject());
        }
        console.log('🔄 触发器:', triggerRows);
      }
    } catch (error) {
      console.error('❌ 查询审计表信息失败:', error.message);
    }
    
    db.close();
  } catch (error) {
    console.error('❌ 设置审计失败:', error);
  }
}

// 执行设置
if (require.main === module) {
  setupAudit();
}

module.exports = setupAudit;